<?php

class ActionRegister2 extends BaseAction
{
    public function run()
    {
        $oProfile = new Profile('register_sole_proprietorship');

        if ( Yii::app()->request->getIsPostRequest() )
        {
            $oProfile->setAttributesFromRequest('aProfile');
            $oProfile->customer_type = 'sole_proprietorship';
            $oProfile->is_resident_rb = 1;
            $oProfile->captcha = Yii::app()->request->getParam('captcha');

            if ( $oProfile->save() )
            {
                $sHash                        = substr(md5(Yii::app()->params['password_sold'].$oProfile->email), 0, 8);
                $oUser                        = new User();
                $oUser->user_login            = rand(1000000000, 9999999999);
                $oUser->user_password         = md5($sHash);
                $oUser->user_cdate            = time();
                $oUser->profile_id            = $oProfile->profile_id;
                $oUser->status                = 'pending';
                $oUser->save();

                while(true)
                {
                    $sVerifyCode  = md5(Yii::app()->params['password_sold'].$oProfile->email.rand(10000000000, 999999999));
                    $oVerifyCode = VerifyCode::model()->findByAttributes(array('code' => $sVerifyCode));

                    if(!(bool)$oVerifyCode)
                    {
                        $oVerifyCode = new VerifyCode();
                        $oVerifyCode->user_id = $oUser->user_id;
                        $oVerifyCode->code = $sVerifyCode;
                        $oVerifyCode->is_confirmed = 0;
                        $oVerifyCode->insert();
                        break;
                    }
                }

                Yii::app()->authManager->assign('user_sole_proprietorship', $oUser->user_id);

                $oEmailNotification = new EmailNotification();
                $oEmailNotification->sendEmailToUserSoleProprietorshipAfterRegister($oUser, $oProfile, $sHash, $sVerifyCode);

                Yii::app()->request->redirect(Yii::app()->createUrl('register2_success'));
            }
        }

        $this->template->oProfile = $oProfile;
    }
}